package com.mzw.bizmq;

import com.mzw.common.ErrorCode;
import com.mzw.constant.CommonConstant;
import com.mzw.constant.ExecutionStatus;
import com.mzw.exception.BusinessException;
import com.mzw.manager.AiManager;
import com.mzw.model.entity.Chart;
import com.mzw.model.entity.User;
import com.mzw.service.ChartService;
import com.mzw.service.EmailService;
import com.mzw.service.UserService;
import com.mzw.utils.SendMessageUtil;
import com.mzw.utils.SseEmitterUtil;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author L1nAn
 */
@Component
@Slf4j
public class BiMessageFailConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private EmailService emailService;
    @Resource
    private UserService userService;

    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_DEAD_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message1, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {

        String[] strings = message1.split(",", 2);
        String message = strings[0];
        log.info("死信队列：{}", message);
        long chartId = Long.parseLong(message);
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(ExecutionStatus.EXECUTION_STATUS_FAILED);
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
//            log.info("死信队列重试次数" + map.get(deliveryTag));
            log.info("更新图表" + chartId + "失败状态时失败");
            channel.basicNack(deliveryTag, false, true);
        }
        SseEmitterUtil.sendMessage(String.valueOf(chartService.getById(chartId).getUserId()), "你的任务执行失败");
        SendMessageUtil.sendMessageFail(emailService,
                userService.getById(chartService.getById(chartId).getUserId()).getUserEmail(),
                "图表" + chartId + chartService.getById(chartId).getExecMessage());
        channel.basicAck(deliveryTag, false);
    }
}
